const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const fs = require('fs')
const path = require('path')

// const SECRET = 'gp20'

const genHash = (password) => {
  // return new Promise((resolve, reject) => {
  //   bcrypt.genSalt(10, function(err, salt) {
  //     bcrypt.hash(password, salt, function(err, hash) {
  //       if (err) {
  //         reject(err)
  //       } else {
  //         resolve(hash)
  //       }
  //     })
  //   })
  // })
  return bcrypt.hash(password, 10)
}

const compare = (password, hash) => {
  return bcrypt.compare(password, hash)
}

const sign = (username) => {
  // const token = jwt.sign({username}, SECRET, {expiresIn: '2 days'})
  var privateKey = fs.readFileSync(path.resolve(__dirname, '../cert/rsa_private_key.pem'));
  var token = jwt.sign({ username }, privateKey, { algorithm: 'RS256', expiresIn: '1 day'});
  return token
}

const verify = (token) => {
  try {
    if (token !== 'null') {
      var cert = fs.readFileSync(path.resolve(__dirname, '../cert/rsa_public_key.pem'))
      const decoded = jwt.verify(token, cert)
      return decoded
    } else {
      return false
    }
  } catch (err) {
    console.log(err)
  }
}

module.exports = {
  genHash,
  compare,
  sign,
  verify
}